import 'dart:async';
import 'dart:convert';
import 'package:web_socket_channel/io.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';

class WsManager {
  static final WsManager _instance = WsManager._internal();

  factory WsManager() => _instance;

  WsManager._internal();

  IOWebSocketChannel? _channel;
  StreamSubscription? _subscription;
  Timer? _reconnectTimer;

  String? _url;
  bool _isConnected = false;

  // bool _isClosing = false;

  final Duration _reconnectInterval = const Duration(milliseconds: 100);
  int? _currentGameId;

  /// 消息回调
  Function(String message)? onMessage;

  //链接成功状态回调
  Function(bool success)? onConnectSuccess;

  bool get isConnected => _isConnected;

  // /// 初始化并连接
  // Future<void> initAndConnect(String url) async {
  //   _url = url;
  //
  //   await _connectInternal();
  // }

  /// 自动根据登录状态连接
  void connectWs() async {
    final token = AppUserManager().token;
    if (token.isEmpty) return;
    final wsUrl = '${AppConfig.wsUrl}/api/ws/$token'.replaceAll('#', '');
    _url = wsUrl;
    clog('daslkjdlksad   $_url');
    await _connectInternal();
  }

  /// 主动断开
  Future<void> disconnect() async {
    try {
      _isConnected = false;
      _reconnectTimer?.cancel();
      _reconnectTimer = null;
      await _subscription?.cancel();
      await _channel?.sink.close();
      _channel = null;
    } catch (e) {
      clog('ws disconnect   $e');
    }
  }

  /// 发送消息
  void send(dynamic data) {
    if (!_isConnected || _channel == null) return;
    final msg = data is String ? data : jsonEncode(data);
    clog('发送消息: $msg');
    _channel!.sink.add(msg);
  }

  /// 内部连接逻辑
  Future<void> _connectInternal() async {
    if (_url == null) return;
    clog('alsdjlkas  ');
    try {
      await disconnect();
    } catch (e) {
      clog('ws disconnect   $e');
    }
    clog('🔗 尝试连接: $_url');

    try {
      _channel = IOWebSocketChannel.connect(Uri.parse(_url!),
          pingInterval: const Duration(seconds: 25));
      _subscription = _channel!.stream.listen(
        (message) {
          clog('💬 WebSocket 收到: $message');
          var data = jsonDecode(message);
          if (data is Map && data['message']?['status'] == 'success') {
            _isConnected = true;
            onConnectSuccess?.call(true);
          } else {
            onMessage?.call(message);
          }
        },
        onDone: () {
          onConnectSuccess?.call(false);
          _handleDisconnect("done");
        },
        onError: (e) {
          onConnectSuccess?.call(false);
          _handleDisconnect("error: $e");
        },
        // cancelOnError: true,
      );

      clog('✅ WebSocket 已连接');

      // 自动恢复订阅
      // if (_currentGameId != null) {
      //   send({'game_id': _currentGameId});
      // }
    } catch (e) {
      _isConnected = false;
      clog('❌ WebSocket 连接异常: $e');
      _handleDisconnect("exception: $e");
    }
  }

  /// 断开与自动重连
  void _handleDisconnect(String reason) {
    _isConnected = false;
    _subscription?.cancel();
    _channel = null;

    clog('⚠️ WebSocket 断开: $reason，3秒后重连...');
    _reconnectTimer?.cancel();
    _connectInternal();
    _reconnectTimer = Timer(_reconnectInterval, _connectInternal);
  }

  /// 游戏订阅
  void beginGameSubscription(int gameId) {
    _currentGameId = gameId;
    send({'game_id': gameId});
  }

  void stopGameSubscription() {
    _currentGameId = null;
    send({'game_id': 0});
  }

  //检查ws是否能够链接上 单独使用
  Future checkCanConnect(
      {required String url,
      required Function(bool success) onConnectSuccess}) async {
    await disconnect();
    String wsUrl = '$url/api/ws/${AppUserManager().token}'.replaceAll('#', '');
    bool isBack = false;
    Future.delayed(const Duration(seconds: 2), () {
      if (isBack == false) {
        onConnectSuccess.call(false);
      }
    });
    _channel = IOWebSocketChannel.connect(Uri.parse(wsUrl));
    _subscription = _channel!.stream.listen(
      (message) {
        clog('WebSocket message checkCanConnect  $message');
        var data = jsonDecode(message);
        if (data is Map && data['message']?['status'] == 'success') {
          onConnectSuccess.call(true);
        }
      },
      onDone: () {
        clog('WebSocket ondone checkCanConnect');
        onConnectSuccess.call(false);
      },
      onError: (error) {
        clog('WebSocket error checkCanConnect  $error');
        onConnectSuccess.call(false);
        // _handleDisconnect("error: $error");
      },
      cancelOnError: false,
    );
  }
}

// import 'dart:async';
// import 'dart:convert';
// import 'package:flutter_09_game/utils/log/utils_log.dart';
// import 'package:web_socket_channel/io.dart';
// import 'package:web_socket_channel/status.dart' as status;
// import 'package:flutter_09_game/config/app_config.dart';
// import 'package:flutter_09_game/user/app_user_manager.dart';
//
// /// WebSocket 管理器（单例模式）
// class WsManager {
//   static final WsManager _instance = WsManager._internal();
//
//   factory WsManager() => _instance;
//
//   WsManager._internal();
//
//   /// 配置参数
//   late String _url;
//
//   // Duration _heartbeatInterval = const Duration(seconds: 30);
//   Duration _reconnectInterval = const Duration(seconds: 3);
//   int _maxReconnectAttempts = 10;
//
//   IOWebSocketChannel? _channel;
//   StreamSubscription? _subscription;
//
//   // Timer? _heartbeatTimer;
//   Timer? _reconnectTimer;
//
//   int _reconnectAttempts = 0;
//   bool _isManuallyClosed = false;
//   bool _isConnected = false;
//   int? _currentGameId;
//
//   /// 回调
//   Function(String message)? onMessage;
//   Function(String state)? onStateChange;
//
//   /// 获取连接状态
//   bool get isConnected => _isConnected;
//
//   /// 初始化
//   Future initAndConnect({
//     required String url,
//     // Duration heartbeatInterval = const Duration(seconds: 10),
//     Duration reconnectInterval = const Duration(seconds: 5),
//     int maxReconnectAttempts = 50,
//   }) async {
//     _url = url;
//     // _heartbeatInterval = heartbeatInterval;
//     clog('  initAndConnect   url $url');
//     _reconnectInterval = reconnectInterval;
//     _maxReconnectAttempts = maxReconnectAttempts;
//     _isManuallyClosed = false;
//     _reconnectAttempts = 0;
//     await _connectInternal();
//   }
//
//   // /// 使用token连接WebSocket
//   // void connectWithToken(String token) {
//   //   if (token.isEmpty) {
//   //     onStateChange?.call("token为空，无法连接");
//   //     return;
//   //   }
//   //
//   //   // String wsUrl =  '${AppConfig.wsUrl}/api/ws/$token';
//   //   // initAndConnect(url: wsUrl);
//   // }
//
//   /// 检查登录状态并自动连接
//   void checkAndConnect() {
//     if (AppUserManager().token.isNotEmpty) {
//       String wsUrl = '${AppConfig.wsUrl}/api/ws/${AppUserManager().token}'
//           .replaceAll('#', '');
//       initAndConnect(url: wsUrl);
//     } else {
//       onStateChange?.call("用户未登录，跳过WebSocket连接");
//     }
//   }
//
//   checkCanConnect(
//       {required String url,
//       required Function(bool success) onConnectSuccess}) async {
//     await disconnect();
//       String wsUrl = '$url/api/ws/${AppUserManager().token}'.replaceAll('#', '');
//     bool isBack = false;
//     Future.delayed(const Duration(seconds: 2), () {
//       if (isBack == false) {
//         onConnectSuccess.call(false);
//       }
//     });
//     // clog('wsmanager   $wsUrl   ${AppUserManager().token}');
//     _channel = IOWebSocketChannel.connect(Uri.parse(wsUrl));
//     _subscription = _channel!.stream.listen(
//       (message) {
//         clog('WebSocket message  $message');
//         var data = jsonDecode(message);
//         if (data is Map && data['message']?['status'] == 'success') {
//           onConnectSuccess.call(true);
//         }
//       },
//       onDone: () {
//         clog('WebSocket ondone');
//         onConnectSuccess.call(false);
//       },
//       onError: (error) {
//         clog('WebSocket error   $error');
//         onConnectSuccess.call(false);
//         // _handleDisconnect("error: $error");
//       },
//       cancelOnError: true,
//     );
//   }
//
//   /// 建立连接
//   // void connect() {
//   //   _isManuallyClosed = false;
//   //   _reconnectAttempts = 0;
//   //   _connectInternal();
//   // }
//
//   Future _connectInternal() async {
//     await disconnect();
//
//     onStateChange?.call("connecting");
//     _isManuallyClosed = false;
//     try {
//       _channel = IOWebSocketChannel.connect(Uri.parse(_url));
//       _subscription = _channel!.stream.listen(
//         (message) {
//           clog('WebSocket message  $message');
//           onMessage?.call(message);
//         },
//         onDone: () {
//           clog('WebSocket ondone');
//           _handleDisconnect("done");
//         },
//         onError: (error) {
//           clog('WebSocket error   $error');
//           _handleDisconnect("error: $error");
//         },
//         cancelOnError: true,
//       );
//
//       // _startHeartbeat();
//       _isConnected = true;
//       onStateChange?.call("connected");
//
//       // 如果有当前游戏订阅，重新发送订阅
//       if (_currentGameId != null) {
//         beginGameSubscription(_currentGameId!);
//       }
//     } catch (e) {
//       _isConnected = false;
//       _handleDisconnect("exception: $e");
//     }
//   }
//
//   /// 发送消息
//   void send(dynamic data) {
//     if (_channel != null) {
//       if (data is String) {
//         _channel!.sink.add(data);
//       } else {
//         clog('发送消息   $data');
//         _channel!.sink.add(jsonEncode(data));
//       }
//     }
//   }
//
//   /// 主动断开
//   Future disconnect() async {
//     _isManuallyClosed = true;
//     _isConnected = false;
//     // _stopHeartbeat();
//     _reconnectTimer?.cancel();
//     await _subscription?.cancel();
//     // status.goingAway
//     await _channel?.sink.close();
//
//     _channel = null;
//     onStateChange?.call("closed");
//   }
//
//   // /// 心跳机制
//   // void _startHeartbeat() {
//   //   _stopHeartbeat();
//   //   _heartbeatTimer = Timer.periodic(_heartbeatInterval, (_) {
//   //     // send({"type": "ping", "time": DateTime.now().toIso8601String()});
//   //   });
//   // }
//
//   // void _stopHeartbeat() {
//   //   _heartbeatTimer?.cancel();
//   //   _heartbeatTimer = null;
//   // }
//
//   beginGameSubscription(int gameId) {
//     _currentGameId = gameId;
//     send({'game_id': gameId});
//   }
//
//   stopGameSubscription() {
//     _currentGameId = null;
//     send({'game_id': 0});
//   }
//
//   /// 断开处理 + 重连逻辑
//   void _handleDisconnect(String reason) {
//     _isConnected = false;
//     // _stopHeartbeat();
//     _subscription?.cancel();
//     _channel = null;
//
//     if (_isManuallyClosed) {
//       onStateChange?.call("closed");
//       return;
//     }
//
//     onStateChange?.call("disconnected: $reason");
//
//     if (_reconnectAttempts < _maxReconnectAttempts) {
//       _reconnectAttempts++;
//       _reconnectTimer?.cancel();
//       _reconnectTimer = Timer(_reconnectInterval, () {
//         onStateChange?.call("reconnecting ($_reconnectAttempts)");
//         _connectInternal();
//       });
//     } else {
//       onStateChange?.call("failed after $_maxReconnectAttempts attempts");
//     }
//   }
// }
